package com.service;

import com.entity.MaintenanceDailyWorkRecord;
import com.repository.MaintenanceDailyWorkRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class MaintenanceDailyWorkRecordService {

    @Autowired
    private MaintenanceDailyWorkRecordRepository maintenanceDailyWorkRecordRepository;

    /**
     * 保存每日作业记录
     * @param maintenanceDailyWorkRecord 每日作业记录
     * @return 保存后的对象
     */
    public MaintenanceDailyWorkRecord save(MaintenanceDailyWorkRecord maintenanceDailyWorkRecord) {
        if (maintenanceDailyWorkRecord.getId() == null) {
            maintenanceDailyWorkRecord.setCreateTime(new Date());
        }
        maintenanceDailyWorkRecord.setUpdateTime(new Date());
        return maintenanceDailyWorkRecordRepository.save(maintenanceDailyWorkRecord);
    }

    /**
     * 根据ID删除每日作业记录
     * @param id ID
     */
    public void deleteById(Integer id) {
        maintenanceDailyWorkRecordRepository.deleteById(id);
    }

    /**
     * 根据ID获取每日作业记录
     * @param id ID
     * @return 每日作业记录
     */
    @Transactional(readOnly = true)
    public Optional<MaintenanceDailyWorkRecord> findById(Integer id) {
        return maintenanceDailyWorkRecordRepository.findById(id);
    }

    /**
     * 分页查询每日作业记录
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<MaintenanceDailyWorkRecord> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return maintenanceDailyWorkRecordRepository.findAll(pageable);
    }

    /**
     * 根据作业类别模糊查询每日作业记录
     * @param workCategory 作业类别
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<MaintenanceDailyWorkRecord> findByWorkCategoryContaining(String workCategory, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return maintenanceDailyWorkRecordRepository.findByWorkCategoryContaining(workCategory, pageable);
    }
}